<template>
  <scroll-view scroll-y="false">
    <view class="container">
      <!-- Logo -->
      <image src="/static/4.png" class="logo"></image>
      <text class="title">来了来了</text>
      <text class="subtitle">轻松工作，多点生活</text>

      <!-- 输入框 -->
      <view class="input-group">
        <input v-model="username" placeholder="请输入用户名" class="input" />
        <input v-model="password" type="password" placeholder="请输入密码" class="input" />
      </view>

      <!-- 记住密码选项 -->
      <view class="remember-me-wrapper">
        <view :class="['custom-checkbox', { checked: rememberPassword }]" @click="toggleRemember">
          <text v-if="rememberPassword" class="checkmark">√</text>
        </view>
        <text class="remember-text">记住密码</text>
      </view>

      <!-- 登录按钮 -->
      <button @click="login" class="login-button" size="mini">登录</button>

      <!-- 底部协议 -->
      <view class="bottom-text">
        <view class="checkbox-wrapper">
          <view :class="['custom-checkbox', { checked: agree }]" @click="toggleAgree">
            <text v-if="agree" class="checkmark">√</text>
          </view>
        </view>
        <text>已阅读并同意 </text>
        <text @click="goto('/pages/service-agreement/service-agreement')" class="link">服务协议</text>
        <text> 和 </text>
        <text @click="goto('/pages/privacy-policy/privacy-policy')" class="link">隐私政策</text>
        <text>，</text>
        <text>各账户资产与权限不互通</text>
      </view>
    </view>
  </scroll-view>
</template>

<script>
import { ref, onMounted } from 'vue'
import { chat, login1 } from "@/uni_modules/byt-ai-agent-uni/common/api";
import {address} from "@/config/conf";

// 定义响应式数据
const username = ref('')
const password = ref('')
const agree = ref(false)
const showDrawer = ref(false)
const rememberPassword = ref(false) // 记住密码状态

// 存储键名
const STORAGE_KEYS = {
  USERNAME: 'rememberedUsername',
  PASSWORD: 'rememberedPassword',
  REMEMBER: 'rememberPasswordStatus'
}

// 切换协议勾选状态
const toggleAgree = () => {
  agree.value = !agree.value
}

// 切换抽屉显示状态
const toggleDrawer = () => {
  showDrawer.value = !showDrawer.value
}

// 使用plus.storage存储数据（5+ API，安卓更稳定）
const setPersistentStorage = (key, value) => {
  try {
    // 优先使用plus.storage
    if (window.plus) {
      plus.storage.setItem(key, value)
    } else {
      // 兼容环境
      uni.setStorageSync(key, value)
    }
  } catch (e) {
    console.error('存储数据失败:', e)
    // 失败时再尝试uni存储
    uni.setStorageSync(key, value)
  }
}

// 获取持久化存储数据
const getPersistentStorage = (key) => {
  try {
    if (window.plus) {
      return plus.storage.getItem(key)
    } else {
      return uni.getStorageSync(key)
    }
  } catch (e) {
    console.error('获取存储数据失败:', e)
    return uni.getStorageSync(key)
  }
}

// 移除持久化存储数据
const removePersistentStorage = (key) => {
  try {
    if (window.plus) {
      plus.storage.removeItem(key)
    } else {
      uni.removeStorageSync(key)
    }
  } catch (e) {
    console.error('移除存储数据失败:', e)
    uni.removeStorageSync(key)
  }
}

// 切换记住密码状态
const toggleRemember = () => {
  rememberPassword.value = !rememberPassword.value

  if (rememberPassword.value) {
    setPersistentStorage(STORAGE_KEYS.USERNAME, username.value)
    setPersistentStorage(STORAGE_KEYS.PASSWORD, password.value)
    setPersistentStorage(STORAGE_KEYS.REMEMBER, 'true')
  } else {
    removePersistentStorage(STORAGE_KEYS.USERNAME)
    removePersistentStorage(STORAGE_KEYS.PASSWORD)
    setPersistentStorage(STORAGE_KEYS.REMEMBER, 'false')
  }
}

const login = async () => {
  if (!agree.value) {
    uni.showToast({title: '请先阅读并同意服务协议和隐私政策', icon: 'none'})
    return
  }
  if (username.value.length === 0 || password.value.length === 0) {
    uni.showToast({title: '请输入账号密码', icon: 'none'})
    return
  }

  // 发送登录请求
  uni.request({
    url: address + '/agentapi/login',
    method: 'POST',
    data: {
      username: username.value,
      password: password.value
    },
    success: (res) => {
      const responseData = res.data
      if (responseData.code === 200) {
        // 登录成功时更新存储
        if (rememberPassword.value) {
          setPersistentStorage(STORAGE_KEYS.USERNAME, username.value)
          setPersistentStorage(STORAGE_KEYS.PASSWORD, password.value)
          setPersistentStorage(STORAGE_KEYS.REMEMBER, 'true')
        }

        uni.setStorageSync('bytToken', responseData.token)
        uni.showToast({title: '登录成功', icon: 'success'})

        setTimeout(() => {
          uni.redirectTo({
            url: '/pages/chat/index'
          })
        }, 1000)
      } else {
        uni.showToast({title: '登录失败', icon: 'none'})
      }
    },
    fail: () => {
      uni.showToast({title: '网络异常', icon: 'none'})
    }
  })

}

// 页面加载时检查是否有记住的密码
onMounted(() => {
  // 等待plus环境准备好
  const checkPlusReady = () => {
    if (window.plus) {
      loadStoredData()
    } else {
      document.addEventListener('plusready', loadStoredData, false)
    }
  }

  const loadStoredData = () => {
    try {
      const rememberStatus = getPersistentStorage(STORAGE_KEYS.REMEMBER)
      const rememberedUsername = getPersistentStorage(STORAGE_KEYS.USERNAME)
      const rememberedPassword = getPersistentStorage(STORAGE_KEYS.PASSWORD)

      if (rememberStatus === 'true' && rememberedUsername && rememberedPassword) {
        username.value = rememberedUsername
        password.value = rememberedPassword
        rememberPassword.value = true
      }
    } catch (e) {
      console.error('加载存储数据失败:', e)
    }
  }

  checkPlusReady()
})

// 页面跳转方法
const goto = (url) => {
  uni.navigateTo({url})
}

export default {
  setup() {
    return {
      username,
      password,
      agree,
      showDrawer,
      rememberPassword,
      toggleAgree,
      toggleDrawer,
      toggleRemember,
      login,
      goto
    }
  }
}
</script>

<style scoped>
/* 样式保持不变 */
.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40rpx;
  background-color: #f5f5f5;
  height: 94vh;
  overflow: hidden;
}

.logo {
  width: 120rpx;
  height: 120rpx;
  margin-top: 200rpx;
}

.title {
  font-size: 48rpx;
  font-weight: bold;
  color: #333;
  margin-top: 40rpx;
}

.subtitle {
  font-size: 28rpx;
  color: #666;
  margin-top: 10rpx;
}

.input-group {
  display: flex;
  flex-direction: column;
  width: 80%;
  margin-top: 100rpx;
}

.input {
  border: 1rpx solid #ccc;
  padding: 20rpx;
  border-radius: 8rpx;
  margin-bottom: 20rpx;
}

.remember-me-wrapper {
  display: flex;
  align-items: center;
  width: 80%;
  margin-top: 10rpx;
  justify-content: flex-start;
}

.remember-checkbox {
  width: 24rpx;
  height: 24rpx;
  border: 2rpx solid #999;
  border-radius: 4rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  transition: background-color 0.3s, border-color 0.3s;
  margin-right: 10rpx;
  cursor: pointer;
}

.remember-checkbox.checked {
  background-color: #007aff;
  border-color: #007aff;
}

.remember-text {
  font-size: 24rpx;
  color: #666;
  margin-left: 10rpx;
  vertical-align: middle;
}

.login-button {
  background-color: #007aff;
  color: white;
  border-radius: 8rpx;
  padding: 20rpx 0;
  width: 80%;
  margin-top: 40rpx;
}

.bottom-text {
  display: flex;
  align-items: center;
  margin-top: 40rpx;
  margin-left: 40rpx;
  margin-right: 40rpx;
  font-size: 24rpx;
  color: #666;
  flex-wrap: wrap;
  width: 80%;
}

.link {
  color: #007aff;
  text-decoration: underline;
  margin-right: 5rpx;
  cursor: pointer;
}

.checkbox-wrapper {
  display: inline-flex;
  align-items: center;
  margin-right: 10rpx;
  cursor: pointer;
}

.custom-checkbox {
  width: 24rpx;
  height: 24rpx;
  border: 2rpx solid #999;
  border-radius: 4rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  transition: background-color 0.3s, border-color 0.3s;
}

.custom-checkbox.checked {
  background-color: #007aff;
  border-color: #007aff;
}

.checkmark {
  color: #fff;
  font-size: 18rpx;
}
</style>
